package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/demo06.do")
public class Demo06Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取响应字节输出流
        ServletOutputStream outputStream = resp.getOutputStream();
        //指定要被下载的文件
        File file = new File("D:\\Coding\\Tool\\build.txt");
        //设置响应头：告诉浏览器 接下来的数据是需要下载的
        resp.setHeader("content-disposition", "attachment;fileName=" + "build.txt");
        //创建文件输入流，读取目标文件
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        int length = 0;
        while ((length = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer);
            outputStream.flush();
        }
        fileInputStream.close();
        outputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //响应中文乱码解决
        //必须在获取流之前调用
        resp.setContentType("text/html;charset=UTF-8");
        //字符输出流 往客户端输出字符串
        PrintWriter writer = resp.getWriter();
        writer.write("你好");
    }
}
